package cn.readjava.controller;

import cn.readjava.util.FtpUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@Controller
public class FtpController {

    @Autowired
    private FtpUtil ftpUtil;

    @GetMapping("/ftp/test")
    public String upload() {
        return "test/upload";
    }

    /**
     * 上传文件
     *
     * @param file
     * @return
     * @throws IOException
     */
    @PostMapping("/ftp/upload")
    @ResponseBody
    public Object uploadImg(@RequestParam("editormd-image-file") MultipartFile file) throws IOException {
        Map<Object, Object> map = new HashMap<>();
        String fileName = file.getOriginalFilename();
        InputStream inputStream = file.getInputStream();
        String suffixName = fileName.substring(fileName.lastIndexOf("."));  // 后缀名
        fileName = UUID.randomUUID() + suffixName; // 新文件名
        Date now = new Date();
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd");
        String datePath = dateFormat.format(now);
        Boolean flag = ftpUtil.uploadFile(datePath, fileName, inputStream);
        if (flag == false) {
            map.put("success", 0);
            map.put("message", "上传失败");
        }
        map.put("success", 1);
        map.put("message", "上传成功");
        map.put("url", ftpUtil.FTP_BASEPATH_SERVER + "/" + datePath + "/" + fileName);
        return map;
    }
}